package org.codingq92.basic.io.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * NIO Client端
 *
 * @author: CodingQ92
 * @date: 2025/6/29 23:12
 */
public class NIOClient {
    public static void main(String[] args) {
        // 创建SocketChannel
        try (SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 18000))) {
            sChannel.configureBlocking(false); // 设置为非阻塞模式
            // 创建缓冲区并写入数据
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            // 发送数据
            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.println("请说:");
                String next = scanner.next();
                byteBuffer.put(next.getBytes());
                byteBuffer.flip();
                // 发送数据
                sChannel.write(byteBuffer);
                byteBuffer.clear();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
